﻿using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Wlx.LogAnalysis.Application.Models;

namespace Wlx.LogAnalysis.Application.Controllers
{
    public class RptFileManager
    {
        //匹配模式：code[空格]measure[空格]Value[空格]Unit[空格]Result[空格]Min[空格]Max[空格]
        //private const string Pattern = "^(\\w+)\\s+(\\S+)\\s+:([\\w-\\.]+)\\s+([\\w-]+)\\s+(\\w+)\\s+([\\w-\\.]+)([\\d|\\.|\\s]+)([\\w-\\.]+)\\s*$";

        private const string PnCodeTextStr = "PNCode";
        private const string StartTimeStr = "StartTime";
        private const string TimeTitleStr = "Start Time:";
        private const string SlotNumberStr = "Slot Number";
        private const string JIGSNStr = "JIG SN";

        public static ImportFileModel FileAnalysis(ImportFileModel fileModel, Regex regex)
        {
            var defaultItems = new Dictionary<string, RangeModel>
            {
                {TemplateItem.Workshop, null},
                {TemplateItem.LineID, null},
                {TemplateItem.Shift, null},
                {TemplateItem.LineCell, null},
                {TemplateItem.Operation, null},
                {TemplateItem.TestBench, null},
                {TemplateItem.MO, null},
                {TemplateItem.MOLineID, null},
                {TemplateItem.PartNumber, null},
                {TemplateItem.ProjectName, null},
                {TemplateItem.ResourceSN, null},
                {TemplateItem.ResourcePN, null},
                {TemplateItem.NumberID, null},
                {TemplateItem.TestSite, null},
                {TemplateItem.SLOT, null},
                {TemplateItem.TestMode, null},
                {TemplateItem.LotType, null},
                {TemplateItem.TransactionUserNO, null},
                {TemplateItem.TransactionUserID, null},
                {TemplateItem.StartTime, null},
                {TemplateItem.SystemTransactionTime, null},
                {TemplateItem.Cmf10, null},
                {TemplateItem.EngineVersion, null},
                {TemplateItem.GuiVersion, null},
                {TemplateItem.TestServiceVersion, null},
                {TemplateItem.ScenarioVersion, null},
                {TemplateItem.JigID, null},
                {TemplateItem.RFDevice, null},
                {TemplateItem.PowerSupply, null},
                {TemplateItem.OtherDevice, null},
                {TemplateItem.TestTime, null},
                {TemplateItem.ServiceError, null},
                {TemplateItem.DefectCodeGroup, null},
                {TemplateItem.DefectCode, null},
                {TemplateItem.DefectCodeDescription, null}
            };
            var newItems = new Dictionary<string, RangeModel>();

            defaultItems[TemplateItem.NumberID] = new RangeModel { Value = fileModel.Name.Split('#')[1] };

            var lines = File.ReadAllLines(fileModel.Path);    //读取文件所有行
            foreach (var line in lines)    //遍历每一行
            {
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }
                if(FillStaticDefaultItems(defaultItems, fileModel, line))
                {
                    continue;
                }

                var matches = regex.Matches(line);   //根据正则表达式匹配每一行，看是否匹配。
                if (matches.Count > 0)    //如果匹配的上
                {
                    var match = matches[0];  //获取匹配数据
                    var methodAndValue = match.Groups[2].Value ?? string.Empty;  //获取方法名+测试值

                    var lastColonIndex = methodAndValue.LastIndexOf(':');
                    var measure = methodAndValue.Substring(0, lastColonIndex).Trim();  //获取“方法名”
                    var value = methodAndValue.Substring(lastColonIndex + 1).Trim();    //获取“测试值”

                    if (defaultItems.ContainsKey(measure))
                    {
                        defaultItems[measure] = new RangeModel { Value = value };
                    }
                    else if (!newItems.ContainsKey(measure))   //判断“方法名”是否有重复，如果没重复，将“方法名”和“测试值”添加到键值对列表中
                    {
                        var minMatch = match.Groups[5].Value ?? string.Empty;
                        var maxMatch = match.Groups[6].Value ?? string.Empty;

                        newItems.Add(measure, new RangeModel
                        {
                            Value = value,
                            Min = minMatch,
                            Max = maxMatch,
                            ValidItem = true
                        });
                    }
                }
            }

            fileModel.KeyValueDic = MergeDictionary(defaultItems, newItems);
            return fileModel;
        }

        private static bool FillStaticDefaultItems(Dictionary<string, RangeModel> dict, ImportFileModel fileModel, string line)
        {
            if (line.StartsWith(TimeTitleStr))
            {
                var time = line.Substring(TimeTitleStr.Length);
                dict[TemplateItem.StartTime] = new RangeModel { Value = time };
                return true;
            }
            if (line.StartsWith(JIGSNStr))
            {
                var jigSn = line.Substring(JIGSNStr.Length + 1);
                dict[TemplateItem.JigID] = new RangeModel { Value = jigSn };
                return true;
            }
            if (line.StartsWith(SlotNumberStr))
            {
                var slotNum = line.Substring(SlotNumberStr.Length + 1);
                dict[TemplateItem.SLOT] = new RangeModel { Value = slotNum };
                return true;
            }
            return false;
        }

        private static Dictionary<string, RangeModel> MergeDictionary(Dictionary<string, RangeModel> dict1, Dictionary<string, RangeModel> dict2)
        {
            var dict3 = new Dictionary<string, RangeModel>();
            foreach(var item in dict1)
            {
                dict3.Add(item.Key, item.Value);
            }
            foreach(var item in dict2)
            {
                dict3.Add(item.Key, item.Value);
            }
            return dict3;
        }
    }

    public class TemplateItem
    {
        public const string Workshop = "Workshop";
        public const string LineID = "Line ID";
        public const string Shift = "Shift";
        public const string LineCell = "Line Cell";
        public const string Operation = "Operation";
        public const string TestBench = "Test Bench";
        public const string MO = "MO";
        public const string MOLineID = "MO Line ID";
        public const string PartNumber = "Part Number";
        public const string ProjectName = "Project Name";
        public const string ResourceSN = "Resource SN";
        public const string ResourcePN = "Resource PN";
        public const string NumberID = "Number ID";
        public const string TestSite = "Test Site";
        public const string SLOT = "SLOT";
        public const string TestMode = "Test Mode";
        public const string LotType = "Lot Type";
        public const string TransactionUserNO = "Transaction User NO";
        public const string TransactionUserID = "Transaction User ID";
        public const string StartTime = "Start Time";
        public const string SystemTransactionTime = "System Transaction Time";
        public const string Cmf10 = "Cmf10";
        public const string EngineVersion = "Engine Version";
        public const string GuiVersion = "Gui Version";
        public const string TestServiceVersion = "Test Service Version";
        public const string ScenarioVersion = "Scenario Version";
        public const string JigID = "Jig ID";
        public const string RFDevice = "RF Device";
        public const string PowerSupply = "Power Supply";
        public const string OtherDevice = "Other Device";
        public const string TestTime = "Test Time";
        public const string ServiceError = "Service Error";
        public const string DefectCodeGroup = "Defect Code Group";
        public const string DefectCode = "Defect Code";
        public const string DefectCodeDescription = "Defect Code Description";
    }
}
